<template>
  <div class="dict-data-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>字典管理</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="字典名称：">
          <el-input v-model="searchForm.dictLabel" placeholder="请输入字典名称" clearable size="small"></el-input>
        </el-form-item>
        <el-form-item label="字典类型：">
          <el-input v-model="searchForm.dictType" placeholder="请输入字典类型" clearable size="small"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="searchForm.status" placeholder="请选择字典状态" clearable size="small">
            <el-option label="正常" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间：">
          <el-date-picker
              v-model="dateRange"
              size="small"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格展示区域 -->
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom: 10px" @click="handleAdd" v-hasPermi="'system:user:add'">添加</el-button>
      <el-button type="primary" style="margin-bottom: 10px" @click="handleExport">导出</el-button>
<!--      删除按钮-->
      <el-button type="danger" style="margin-bottom: 10px" @click="handleDeleteBatch" v-hasPermi="'system:user:delete'">批量删除</el-button>
      <el-table
          ref="multipleTable"
          :data="pageData.data"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="dictCode" label="字典编码" width="120"></el-table-column>
        <el-table-column prop="dictLabel" label="字典标签" width="120"></el-table-column>
        <el-table-column prop="dictValue" label="字典键值" show-overflow-tooltip></el-table-column>
        <el-table-column prop="dictSort" label="字典排序" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="状态" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)" style="color: #f56c6c">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container" style="margin-top: 15px; text-align: right">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageData.pageNo"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.totalCount"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
        :title="formData.dictCode ? '编辑字典' : '添加字典'"
        :visible.sync="dialogVisible"
        width="500px"
        append-to-body
        @close="handleDialogClose"
    >

      <el-form ref="dictForm" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input v-model="formData.dictLabel" placeholder="请输入字典标签"/>
        </el-form-item>
        <el-form-item label="字典类型" prop="dictValue">
          <el-input v-model="formData.dictType" placeholder="请输入字典类型"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'SysDictDataTable',
  data() {
    return {
      dialogVisible: false,
      pageData: {
        data: [],
        pageNo: 1,
        pageSize: 5,
        totalCount: 0,
        totalPageCount: 0
      },
      dateRange: [],
      searchForm: {
        dictLabel: '',
        dictType: '',
        status: '',
        startDate: '',
        endDate: ''
      },
      formData: {
        dictLabel:'',
        dictType:'',
        status:'',
        remark: '',
        dictCode:''
      },
      // 关键修复：添加表单验证规则
      formRules: {
        dictLabel: [
          { required: true, message: '请输入字典标签', trigger: 'blur' }
        ],
        dictSort: [
          { required: true, message: '请输入字典排序', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      multipleSelection: [] // 用于存储选中的数据
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.doSearch();
    });
  },
  methods: {
    doSearch() {
      if (this.dateRange && this.dateRange.length === 2) {
        this.searchForm.startDate = this.dateRange[0] + ' 00:00:00';
        this.searchForm.endDate = this.dateRange[1] + ' 23:59:59';
      }

      const params = {
        ...this.searchForm,
        pageNo: this.pageData.pageNo,
        pageSize: this.pageData.pageSize
      };

      this.$axios.get("/api/sys/dictData/list", {params})
          .then((res) => {
            if (res.data.code === 200) {
              this.pageData.data = res.data.data.records || [];
              this.pageData.pageNo = res.data.data.current || 1;
              this.pageData.pageSize = res.data.data.size || 5;
              this.pageData.totalCount = res.data.data.total || 0;
              this.pageData.totalPageCount = res.data.data.pages || 0;
            } else {
              this.$message.error(res.data.msg || '获取数据失败');
            }
          })
          .catch((err) => {
            console.error('请求失败：', err);
            this.$message.error('网络异常，请稍后重试');
          });
    },

    formatDate(date) {
      if (!date) return '';
      try {
        let dateObj;
        if (typeof date === 'string') {
          dateObj = new Date(date.replace(/-/g, '/').replace('T', ' ').replace(/\.\d+/, ''));
        } else if (typeof date === 'number') {
          dateObj = new Date(date);
        } else {
          dateObj = date;
        }

        if (isNaN(dateObj.getTime())) return '';

        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        const hours = String(dateObj.getHours()).padStart(2, '0');
        const minutes = String(dateObj.getMinutes()).padStart(2, '0');
        const seconds = String(dateObj.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (e) {
        console.error('日期格式化错误:', e);
        return '';
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val; //更新选中的行数据
    },

    handleSizeChange(val) {
      this.pageData.pageSize = val;
      this.pageData.pageNo = 1;
      this.doSearch();
    },

    handleCurrentChange(val) {
      this.pageData.pageNo = val;
      this.doSearch();
    },

    resetForm() {
      this.formData = {
        dictLabel:'',
        dictType:'',
        status:'',
        remark: '',
      };
      // 清除表单验证
      if (this.$refs.dictForm) {
        this.$refs.dictForm.clearValidate();
      }
    },

    handleAdd() {
      this.resetForm();
      this.dialogVisible = true;
    },

    handleEdit(row) {
      this.resetForm();
      this.$axios.get("/api/sys/dictData/view/" + row.dictCode).then((res) => {
        if (res.data.code === 200) {
          this.formData = {
            ...res.data.data,
            status: res.data.data.status.toString(),
          };
          this.formData.dictCode=row.dictCode;
          console.log("id是"+ this.formData.dictCode)
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch((err) => {
        console.error('请求失败：', err);
      });
      this.dialogVisible = true;
    },

    handleDialogClose() {
      this.resetForm();
    },

    submitForm() {
      this.$refs.dictForm.validate(valid => {
        if (valid) {
          console.log("再次观看id"+ this.formData.dictCode)
          if (this.formData.dictCode == null) {
            // 新增
            this.$axios.post("/api/sys/dictData/add", this.formData).then((res) => {
              if (res.data.code == 200) {
                this.$message.success('添加成功');
                this.dialogVisible = false;
                this.doSearch();
              } else {
                this.$message.error(res.data.msg || '添加失败');
              }
            }).catch((err) => {
              console.error('请求失败：', err);
              this.$message.error('网络异常，请稍后重试');
            });
          } else {
            // 修改
            this.$axios.put("/api/sys/dictData/edit", this.formData).then((res) => {
              if (res.data.code == 200) {
                this.$message.success('修改成功');
                this.dialogVisible = false;
                this.doSearch();
              } else {
                this.$message.error(res.data.msg || '修改失败');
              }
            }).catch((err) => {
              console.error('请求失败：', err);
              this.$message.error('网络异常，请稍后重试');
            });
          }
        } else {
          this.$message.error('请填写必填字段');
          return false;
        }
      });
    },
    handleDelete(row) {
      this.$confirm(`确定删除字典【${row.dictLabel}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete("/api/sys/dictData/delete/" + row.dictCode).then((res) => {
          if (res.data.code === 200) {
            this.$message.success('删除成功');
            this.doSearch();
          } else {
            this.$message.error(res.data.msg || '删除失败');
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    //导出
    handleExport(){
      this.$axios.get("/api/sys/dictData/export",
          {
            params:this.searchForm,
            responseType:"blob" //指定响应的类型
          }).then((res)=>{
        let blob=new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        let url=window.URL.createObjectURL(blob);
        let a = document.createElement('a')
        a.href = url

        const contentDisposition = res.headers['content-disposition']
        let fileName = 'xxx.xlsx'
        if (contentDisposition) {
          // 解析响应头中的文件名（后端需设置正确的header）
          const match = contentDisposition.match(/filename=(.+)/)
          if (match && match[1]) {
            fileName = decodeURIComponent(match[1])
          }
        }
        // 指定下载后的文件名
        a.download = fileName
        //test

        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(a)

        this.$message.success("导出成功");
      }).catch((err)=>{
        this.$message.error("导出失败");
        console.log(err);
      })
    },
    handleDeleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一条数据');
        return;
      }

      // 提取选中数据的 dictCode
      const ids = this.multipleSelection.map(item => item.dictCode);
      console.log("ids:", ids);

      this.$confirm(`确定删除选中的 ${ids.length} 条字典数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 修改这里：直接传递数组，而不是对象
        this.$axios.post("/api/sys/dictData/deleteBatch", ids, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
            .then((res) => {
              if (res.data.code === 200) {
                this.$message.success('删除成功');
                this.doSearch(); // 刷新表格数据
                this.multipleSelection = []; // 清空选择
              } else {
                this.$message.error(res.data.msg || '删除失败');
              }
            })
            .catch((err) => {
              console.error('请求失败：', err);
              this.$message.error('网络异常，请稍后重试');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
    }
}
</script>

<style scoped>
.dict-data-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  min-height: 500px;
}
</style>